﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jint.Native;
using MongoDB.Driver;
using MongoDB.Bson;
using Jint;
using MongoDB.Driver.Builders;

namespace jintTest
{
   class DbCollection : JsObject
   {
      private readonly MongoCollection<BsonDocument> _collection;
      private readonly JintEngine _jsonEngine;

      public DbCollection(MongoCollection<BsonDocument> collection, JintEngine jsonEngine)
      {
         _collection = collection;
         _jsonEngine = jsonEngine;

         // Registers
         this["where"] = new JsFunctionWrapper(Where, null);
      }

      public JsInstance Where(JsInstance[] args)
      {
         QueryDocument query = null;
         if (args.Length > 0)
         {
            string jsonStr = args[0].ToJson();
            query = new QueryDocument(BsonDocument.Parse(jsonStr));
         }
         var mongoCursor = _collection.Find(query);
         BsonArray allResults = new BsonArray();
         int index = 0;
         foreach (var bsonDocument in mongoCursor)
         {
            allResults.Add(bsonDocument);
            index++;
         }
         string jsonResult = allResults.ToJson();
         JsInstance jintResult = (JsInstance)_jsonEngine.Run("eval((" + jsonResult + "));");
         return jintResult;
      }
   }
}
